
import api from '../../utils/api'
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast'
const app = getApp()
var WSCoordinate = require('../../utils/WSCoordinate.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imageBaseURL: app.imageBaseURL,
    imageResizeParams: app.imageResizeParams,
    activeObj:'',
    actid:'',
    state:'',
    gourl:'',

    //倒计时
    day:'00',
    time: 30 * 60 * 60 * 1000,
    timeData: {},
  },
  //倒计时
  onChange(e) {
    this.setData({
      timeData: e.detail,
    });
  },
  navhome(){
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  gomenuPage(e){
    let url = e.currentTarget.dataset.navurl
    let id = e.currentTarget.dataset.activeid
    wx.navigateTo({
      url: url + '?id=' + id,
    })
  },
  //点赞评论
  async zanPinglun(e){
    if( !api.isauth() ){
      wx.navigateTo({
        url: this.data.gourl
      })
      return
    }
    let commentid = e.currentTarget.dataset.commentid;
    let id = e.currentTarget.dataset.id;
    let data={}
    data['flag'] = 'discuss_like'
    data['discussid'] = commentid
    const {recode, result, message} = await api.send(data,{'isloading':false})
    if(recode === 'SUCC') {
      this.getDetail(id)
    }else {
      Toast(message)
    }
  },
  //撤回报名
  async recall(e){
    let id = e.currentTarget.dataset.activeid;
    let data={}
    data['flag'] = 'active_chehui'
    data['activityid'] = id
    data['recall_reason'] = '撤回原因'
    const {recode, result, message} = await api.send(data,{'isloading':false})
    if(recode === 'SUCC') {
      this.getDetail(id)
    }else {
      Toast(message)
    }

  },
  //立即报名参加
  navActiveApply:api.throttle(function (e) {
    let _this = this
    wx.requestSubscribeMessage({
      tmplIds: ['ooKHT3i6PuzpM2dnvaTUAxBft8Nl_HlSfqQEoywg4uc','UzRipOWtG48sa7Q6F5Sc3CkoOnliQRbqyJ4YfzUNABo','AXevXERNGpaWspYj-vT6EWF3HFrIdC5Q1RDgi-5UDzU'],
      success (res) { 
        console.log(res)
        _this.navActiveApply1(e)
      },
      fail(res){
        console.log(res)
        _this.navActiveApply1(e)
      }
    })
  }),
  navActiveApply1(e){
    console.log(e)

    if( !api.isauth() ){
      wx.navigateTo({
        url: this.data.gourl
      })
      return
    }
    
    let allnum = e.currentTarget.dataset.allnum;
    let applied = e.currentTarget.dataset.applied;
    if(applied >=allnum){
      Toast('报名已满')
      return
    }
    let id = e.currentTarget.dataset.activeid
    let bmandshstr = e.currentTarget.dataset.bmandshstr
    wx.navigateTo({
      url: '/pages/index_active_apply/index?id=' + id + '&bmandshstr=' + bmandshstr,
    })

  },
  //点赞
  async zan(e){
    if( !api.isauth() ){
      wx.navigateTo({
        url: this.data.gourl
      })
      return
    }

    let status = e.currentTarget.dataset.status == 0 ? 1 : 0;
    let id = e.currentTarget.dataset.id;
    let data={}
    data['flag'] = 'activity_like'
    data['activityid'] = id
    data['status'] = status
    const {recode, result, message} = await api.send(data,{'isloading':false})
    if(recode === 'SUCC') {
      this.getDetail(id)
    }else {
      Toast(message)
    }
  },
  //关注 关注状态，0取消关注，1关注
  async focus(e){

    if( !api.isauth() ){
      wx.navigateTo({
        url: this.data.gourl
      })
      return
    }
    
    let status = e.currentTarget.dataset.status == 0 ? 1 : 0;
    let id = e.currentTarget.dataset.id;
    let data={}
    data['flag'] = 'activity_focus'
    data['activityid'] = id
    data['status'] = status
    const {recode, result, message} = await api.send(data,{'isloading':false})
    if(recode === 'SUCC') {
      this.getDetail(id)
    }else {
      Toast(message)
    }
  },
  //时间戳计算天数
  countDown(endTimeStamp) {
    var nowTimeStamp = new Date().getTime()
    var time = {}
    if (endTimeStamp > nowTimeStamp) {
      var mss = endTimeStamp - nowTimeStamp;
      var days = parseInt(mss / (1000 * 60 * 60 * 24))
      var hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
      var minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60))
      var seconds = parseInt((mss % (1000 * 60)) / 1000)
      time = {
        day: days < 10 ? "0" + days : days,
        hour: hours < 10 ? "0" + hours : hours,
        minute: minutes < 10 ? "0" + minutes : minutes,
        second: seconds < 10 ? "0" + seconds : seconds,
        mss: mss,
      }
    } else {
      time = {
        day: '00',
        hour: '00',
        minute: '00',
        second: '00',
        mss: '00',
      }
    }
    this.setData({
      day:time.day,
      time:mss

    })
    console.log(time)
    return time
  },
  
  //详情
  async getDetail(activityid){
    let data={}
    data['flag'] = 'activity_once'
    data['activityid'] = activityid
    const {recode, result, message} = await api.send(data,{'isloading':false})
    if(recode === 'SUCC') {
      result.imgurl = api.checkurl(result.imgurl)
      if(!result.likenum ) result.likenum = 0
      if(!result.apply.join) result.apply.join = 0
      
      let state = ''
      if (result.state == 1) {
        state = '未发布'
    }else if (result.state == 2) {
      state = '已发布'
    }else if (result.state == 3) {
      state = '正在报名'
    }else if (result.state == 4) {
      state = '暂停报名'
    }else if (result.state == 5) {
      state = '进行中'
    }else if (result.state == 6) {
      state = '已取消'
    }else if (result.state == "7") {
      state = '活动已结束'
    }
    //获取时间戳
    let endTime = result.end_timestamp*1000;
    this.countDown(endTime)

    result.category = parseInt(result.category)
      this.setData({
        activeObj:result,state
      })
      console.log(this.data.time)
    
    }else {
      // Toast(message)
    }

  },

  //打电话
  callphone(){
    let phone = this.data.activeObj.responsibility[0].tel||0
    wx.makePhoneCall({
      phoneNumber: phone
    }).then(res => console.log('res: ', res))
  },
  openmap(){
    let lat = parseFloat(this.data.activeObj.location.lat||0)
    let lng = parseFloat(this.data.activeObj.location.lng||0)
    let point = WSCoordinate.transformFromBaiduToGCJ(lat, lng);
    console.log(lat,lng)
    wx.openLocation({
      latitude:point.latitude,
      longitude:point.longitude,
      scale: 18
    }).then(res => console.log('res: ', res))
  },
  
  jumpyouth(){
     wx.navigateTo({
       url: '/pages/index_youthhome_detail/index?youthid='+this.data.activeObj.community.id,
     })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let id = options.id||''
    if( options.scene ){
      let obj = api.decodeurl(options.scene)
      if( obj ) id = obj.id||''
    }
    let gourl = '/pages/login/index?url='+encodeURIComponent('/pages/index_active_detail/index?id='+id)
    this.setData({actid:id, gourl})
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getDetail(this.data.actid)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

    /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    api.sendshare(this.data.actid,3)
    return {
      title: '['+this.data.activeObj.actname.name+']活动详情',
      path: `/pages/index_active_detail/index?id=${this.data.actid}`,
      success(res){
        console.log('转发成功' + res)
      },
      fail(res){
        console.log('转发失败' + res);
      }
    }
  }
})